package cn.bincker.mycaptcha.basic.filter;

import cn.bincker.mycaptcha.basic.CaptchaGuard;
import cn.bincker.mycaptcha.basic.VerifyFailHandler;
import cn.bincker.mycaptcha.basic.exception.CaptchaVerifyFailException;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * 拦截需要验证的请求，响应自定义内容
 */
@WebFilter
public class MyCaptchaFilter implements Filter {
    private final List<CaptchaGuard> guards;
    private final VerifyFailHandler verifyFailHandler;

    public MyCaptchaFilter(List<CaptchaGuard> guards, VerifyFailHandler verifyFailHandler) {
        this.guards = guards;
        this.verifyFailHandler = verifyFailHandler;
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        var httpRequest = (HttpServletRequest) request;
        var httpResponse = (HttpServletResponse) response;
        for (CaptchaGuard guard : guards) {
            if(guard.match(httpRequest)){
                try {
                    guard.check(httpRequest, httpResponse);
                }catch (CaptchaVerifyFailException e){
                    verifyFailHandler.handle(httpRequest, httpResponse, e);
                    return;
                }
                break;
            }
        }
        if(httpResponse.isCommitted()) return;
        chain.doFilter(request, response);
    }
}
